package jdbc.chapter_Jan_1_2019;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.sql.*;

public class DjdbcU {
    private static String driver;
    private static String url;
    private static String user;
    private static String possword;
    private static Connection connection;
    static {
        File file = new File("\\hx_px\\src\\poc.xml");
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        DocumentBuilder builder= null;
        try{
        builder = factory.newDocumentBuilder();
        Document doc= null;
        doc = builder.parse(file);
        NodeList nn=doc.getElementsByTagName("VALUE");
        for (int i = 0; i < nn.getLength(); i++) {
                    driver=doc.getElementsByTagName("driver").item(i).getTextContent();
                    url=doc.getElementsByTagName("url").item(i).getTextContent();
                    user=doc.getElementsByTagName("user").item(i).getTextContent();
                    possword=doc.getElementsByTagName("possword").item(i).getTextContent();
                   }
            connection= DriverManager.getConnection(url,user,possword);
        Class.forName(driver);
            System.out.println("连接成功");
    }catch (Exception e){
            System.out.println(e);
        }
    }
    public static ResultSet selectSql(String sql,Object... parment) throws SQLException {
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        for (int a=0;a<parment.length;a++){
            preparedStatement.setObject(a+1,parment[a]);
        }
        return preparedStatement.executeQuery();
    }
    public static int uptata(String sql,Object... parment) throws SQLException {
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        for (int a=0;a<parment.length;a++){
            preparedStatement.setObject(a+1,parment[a]);
        }
        return preparedStatement.executeUpdate();
    }
    public static int uptata(String sql) throws SQLException {
        PreparedStatement preparedStatement=connection.prepareStatement(sql);

        return preparedStatement.executeUpdate();
    }

}


